package com.task.src.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.task.src.eum.Status;
import com.task.src.util.ResponseResult;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest rqs= (HttpServletRequest) request;
        String uri=rqs.getRequestURI();
        if(uri.startsWith("/my")||uri.startsWith("/task")||uri.startsWith("/to")){
            HttpSession session=rqs.getSession();
            Object uid=session.getAttribute("userid");
            if(uid==null){
                ResponseResult res=new ResponseResult();
                res.setCode(500);
                res.setMessage(Status.NO_LOGIN);

                //将对象转换为JSON传给前端
                String json=new ObjectMapper().writeValueAsString(res);
                HttpServletResponse resp=(HttpServletResponse) response;
                resp.setContentType("application/json;charset=utf8");
                resp.getWriter().write(json);
                return;
            }
        }
        //放行
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
